import { useAppDispatch, useAppSelector } from '@/hook/useRedux';
import { useEffect, useState } from 'react';
import clsx from 'clsx';

import classes from './style.module.css';

import { changeAnchor } from './switcher';
import { Button } from '../ui/button';
import { AlertAnswer } from '../Customs/AlertAnswer';

import { Separator } from '@/components/ui/separator';
import { IfElse } from '../IfElse/IfElse';
import { CardDetails } from '@/components/CardDetails';
import { TextArea } from '../Customs';
import { SendIcon, } from '../Icons';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { TaskCardComments } from '../TaskCard';
import { addFileTask, getTask } from '@/redux/tasks/tasksSlice';
import { api } from '@/axios/instance';
import { FileSelector } from '../FileSelector/FileSelector';
import { CustomDrawerSkeleton } from './CustomDrawerSkeleton';
import { TaskCardCheckbox } from '../TaskCard/TaskCardCheckbox';
import { AdvancedButton, AdvancedButtonProps } from '../AdvancedButton/AdvancedButton';
import { AdvancedButtonMap } from '../AdvancedButton/AdvancedButtonMap';
import { HistoryItem } from '../History/HistoryItem';
import { HistoryItemMap } from '../History/HistoryItemMap';

interface Props {
  open: boolean;
  anchor: string;
  onClose: () => void;
  data: number;
}

export const CustomDrawer = ({ open, anchor, onClose, data }: Props) => {
  const { drawer, animate, hidden, header } = classes;


  const dispath = useAppDispatch()
  const { status, taskDrawer } = useAppSelector((state) => state.tasks)


  useEffect(() => {
    dispath(getTask(data))
  }, [data]);

  const [height, setHeight] = useState(false);
  const [activeTab, setActiveTab] = useState('comments');

  const [task, setTask] = useState<Task | null>(null);
  const [removeTask, setRemoveTask] = useState(false);
  const [isShowSubs, setIsShowSubs] = useState(false);
  const [activeTask, setActiveTask] = useState<TaskItem | null>(null)

  const [aciveTaskId, setAciveTaskId] = useState(task?.id)

  const dispatch = useAppDispatch()

  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    // @ts-ignore
    setTask((prev) => ({ ...prev, name: e.target.value }));
  };

  const onTaskSaveName = () => {
    api.post('/api/TaskBoard/task/save', {
      task_id: data,
      // @ts-ignore
      name: task.name
    })
  }


  const handleClickClose = () => {
    onClose();
    // setTask(null);
  };

  const handleCancelRemove = () => {
    setRemoveTask(false);
  };

  const handleAccessRemove = () => {
    setRemoveTask(false);
    // task && deleteTask(task.id.toString());
    handleClickClose();
  };

  const changeTab = (value: string) => {
    if (activeTab === value) {
      setHeight(prev => !prev)
    }
    if (height === false && activeTab !== value) {
      setHeight(false)
      setActiveTab(value)
    }
    if (activeTab !== value) {
      setHeight(true)
    }
    setActiveTab(value)

  }

  const sendFiles = async (uploadFiles: File[]) => {
    let formDataFiles = new FormData();
    formDataFiles.append('task_id', `${activeTask?.id}`);
    uploadFiles.forEach((file, i: number) => {
      formDataFiles.append(`files[${i}]`, file);
    });
    formDataFiles.append('gid', `${activeTask?.files_gid || ''}`);
    dispatch(addFileTask({ file: formDataFiles, taskId: activeTask.id, colId: task.column_id }))
  };

  const classForLabelTitle = 'grow  has-[:checked]:text-white has-[:checked]:bg-[#384455] bg-[#8696A6] rounded-[8px] px-[18px] text-[18px] py-[12px] text-center cursor-pointer'
  const classForTitleLabelSub = 'grow bg-[#f1f5f7] px-[12px] py-[8px] text-[12px] text-[#8696A6] '

  const onChangeTaskRadio = ({ e, type }: { e: React.ChangeEvent<HTMLInputElement>, type: 'task' | 'subtask' }) => {
    setAciveTaskId(+e.target.value)
    if (type === 'task') {
      setActiveTask(taskDrawer)
    } else {
      const subtask = taskDrawer?.subtasks.filter((sub: Task) => sub.id === +e.target.value)
      setActiveTask(...subtask)
    }
  }

  useEffect(() => {
    if (status === 'success') {
      setTask(taskDrawer)
      setAciveTaskId(taskDrawer.id);
      setActiveTask(taskDrawer)
    }
  }, [status]);

  const tabButtonVariants: Pick<AdvancedButtonProps, 'variant' | 'accent' | 'type'> = {
    variant: 'accent',
    accent: 'underline',
    type: 'button',
  }

  const tabButtons: AdvancedButtonProps[] = [
    {

      iconRight: 'Comments',
      children: 'Комментарии',
      onClick: () => changeTab('comments'),
      value: 'task',
      active: activeTab === 'comments' ? 'selected' : null,
      ...tabButtonVariants
    },
    {
      iconRight: 'Files',
      children: 'Файлы',
      onClick: () => changeTab('files'),
      active: activeTab === 'files' ? 'selected' : null,
      ...tabButtonVariants
    },
    {
      iconRight: 'History',
      children: 'История',
      onClick: () => changeTab('history'),
      active: activeTab === 'history' ? 'selected' : null,
      ...tabButtonVariants
    },
    {
      icon: 'X',
      iconSize: 12,
      onClick: () => setHeight(false),
      variant: 'accent',
      className: 'ml-auto'
    }
  ]


  return (
    <>
      <div
        tabIndex={-1}
        className={`${drawer} ${open && animate} ${!open && hidden
          } ${changeAnchor(anchor, classes)} flex`}
      >
        <div className={header}>
          <IfElse>
            <IfElse.When isTrue={!!task?.id}>
              <AdvancedButton icon='Trash' variant={'accent'} onClick={() => setRemoveTask(true)} />
              <Separator orientation='vertical' className='h-full' />
              <AdvancedButton icon='X' iconSize={14} variant={'accent'} onClick={handleClickClose} />
              <AlertAnswer
                open={removeTask}
                cancel={handleCancelRemove}
                accept={handleAccessRemove}
              />
            </IfElse.When>
            <IfElse.Else>
              <h1>Loading</h1>
            </IfElse.Else>
          </IfElse>
        </div>
        <div className='w-full p-4 flex flex-wrap gap-2' >
          <label htmlFor={task?.id.toString()} className={`${classForLabelTitle} w-full text-white`} >
            <input type="radio" className='hidden' name="taskSelect" id={task?.id.toString()} checked={aciveTaskId === task?.id} value={task?.id} onChange={(e) => onChangeTaskRadio({ e, type: 'task' })} />
            <span>{task?.name}</span>
          </label>
          {
            task?.subtasks.map(subtask => (
              <label key={subtask.id} className={`${classForLabelTitle} ${classForTitleLabelSub}`} htmlFor={subtask.id.toString()} >
                <input className='hidden' type="radio" name="taskSelect" id={subtask.id.toString()} checked={aciveTaskId === subtask?.id} value={subtask?.id} onChange={(e) => onChangeTaskRadio({ e, type: 'subtask' })} />
                <span>{subtask.name}</span>
              </label>))
          }
        </div>
        {
          status === 'loading' ? <CustomDrawerSkeleton /> : <>
            <div className={clsx(classes.drawerContent, 'relative flex-grow overflow-y-auto flex flex-col gap-2')}>
              <IfElse>
                <IfElse.When isTrue={!!task?.id}>
                  <div className='space-x-7 ' >
                    <div className='flex gap-2' >
                      <TaskCardCheckbox taskData={activeTask} />
                      <TextArea// @ts-ignore
                        defaultValue={data?.name}
                        // @ts-ignore
                        value={activeTask?.name}
                        onChange={handleInputChange}
                        placeholder='Название задачи'
                        onListenerBlur={onTaskSaveName}
                        height={38}
                        className='text-xl'
                        autoHeight
                      />
                    </div>
                    <CardDetails data={activeTask} />
                    <TextArea
                      // @ts-ignore
                      defaultValue={activeTask?.text}
                      // @ts-ignore
                      value={activeTask?.text}
                      // @ts-ignore
                      onChange={(e) => setActiveTask(p => ({ ...p, text: e?.target.value }))}
                      placeholder='Описание подзадачи'
                      className='text-sm mt-0 py-[14px] px-[20px] bg-slate-50 w-[90%]'
                      height={48}
                    />
                  </div>
                </IfElse.When>
                <IfElse.Else>
                  <h1>Loading...</h1>
                </IfElse.Else>
              </IfElse>
            </div>
            <div className={` w-full flex-shrink-0 left-0  transition-all bottom-0 flex flex-col`} >
              <Tabs defaultValue='comments' className='w-full h-full flex flex-col' value={activeTab} >
                <div className={`${height ? 'h-[300px] py-2 opacity-100' : 'h-[0px] py-0 opacity-0'}  border-t transition-all px-4 overflow-hidden`} >
                  <TabsContent value='comments' >
                    <TaskCardComments comments={activeTask?.comments} taskId={activeTask?.id} msg={false} />

                  </TabsContent>
                  <TabsContent value='files' className='h-full' >
                    <div className='w-full py-3 px-1 shrink grow overflow-y-auto h-full' >
                      {
                        activeTask?.files.length > 0 ?
                          <ul className='w-full' >
                            {activeTask?.files.map(file => <li key={file.small} className='h-[90px] border-b flex gap-3' >
                              <div className='h-full aspect-[40/27]  object-cover' >
                                <img src={file.small} alt="" className=' object-cover h-full w-full' />
                              </div>
                              <div>
                                {file.type}
                              </div>
                            </li>)}
                          </ul> : <h1>Нет файлов</h1>
                      }
                    </div>
                  </TabsContent>
                  <TabsContent value='history' className='h-full' >
                    <div className='w-full px-1 shrink grow overflow-y-auto h-full' >
                      <div className='flex justify-between border-b pb-1 px-2 mb-1 sticky top-0 bg-white z-100' >
                        <span>Исполнитель</span>
                        <span>Действие</span>
                        <span>Дата</span>
                      </div>
                      {activeTask?.actions && <HistoryItemMap actions={activeTask?.actions} />}
                    </div>
                  </TabsContent>
                </div>

                <div className='w-full flex justify-start bg-white gap-6 px-4 border-t rounded-none z-10 py-2' >
                  <AdvancedButtonMap actions={tabButtons} />
                </div>

                <div className='h-14 px-4' >

                  <TabsContent value="comments" className={`grow flex-col  mt-auto `} >
                    <div className='w-full flex border p-3 mt-auto' >
                      <SendIcon className='ml-auto' color='#ddd' />
                    </div>
                  </TabsContent>
                  <TabsContent value='files' className={` flex-col grow ${activeTab === 'files' ? ' flex' : 'hidden'}  overflow-y-auto mt-0 `} >
                    <FileSelector setFiles={sendFiles} >
                      <Button className={` mt-auto border-dashed border bg-transparent text-slate-400  bottom-0 bg-slate-100 p-2 w-full h-full`} variant={'ghost'} >
                        Добавить файл(ы)
                      </Button>
                    </FileSelector>
                  </TabsContent>
                  <TabsContent value="history" className={`grow flex-col  mt-auto `} >
                    {activeTask?.actions && <HistoryItem  {...activeTask?.actions[activeTask?.actions.length - 1]} />}
                  </TabsContent>
                </div>
              </Tabs>
            </div>
          </>
        }
      </div >
    </>
  );
}
